import axios from 'axios'

const API_BASE = import.meta.env.VITE_APP_API_URL

// 天气数据接口
export interface WeatherData {
  city: string
  current?: CurrentWeather
  forecast?: ForecastDay[]
  lastUpdated: string
}

export interface CurrentWeather {
  temp: number
  text: string
  humidity: number
  windSpeed: number
  windDir: string
  pressure: number
  vis: number
}

export interface ForecastDay {
  date: string
  maxTemp: number
  minTemp: number
  text: string
  windDir: string
  windSpeed: number
  humidity: number
  precip: number
}

export interface WeatherAlert {
  id: string
  type: string
  level: string
  title: string
  description: string
  startTime: string
  endTime: string
  affectedAreas: string
}

export interface ProductionImpact {
  city: string
  activityType: string
  currentWeather?: CurrentWeather
  alerts: WeatherAlert[]
  recommendations: string[]
  analysisTime: string
}

export interface WeatherSummary {
  summary: string
  timestamp: string
}

export interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
  timestamp: string
}

// 生产数据接口
export interface ProductionDashboard {
  totalOrders: number
  completedOrders: number
  pendingOrders: number
  delayedOrders: number
  totalEquipment: number
  runningEquipment: number
  maintenanceEquipment: number
  totalWorkers: number
  activeWorkers: number
  onBreakWorkers: number
  productionEfficiency: number
  qualityRate: number
  safetyScore: number
  weatherAlerts: number
  lastUpdated: string
}

export interface ProductionOrder {
  id: string
  name: string
  type: string
  status: string
  priority: string
  startDate: string
  dueDate: string
  progress: number
  assignedWorkers: number
  estimatedHours: number
  actualHours: number
  weatherDependent: boolean
}

export interface EquipmentStatus {
  id: string
  name: string
  type: string
  status: string
  temperature: number
  humidity: number
  efficiency: number
  lastMaintenance: string
  nextMaintenance: string
  weatherSensitive: boolean
}

export interface EquipmentHealth {
  equipmentId: string
  overallHealth: number
  temperature: number
  vibration: number
  noise: number
  pressure: number
  flowRate: number
  lastCalibration: string
  weatherSensitivity: number
  recommendations: string[]
}

export interface SafetyIncident {
  id: string
  type: string
  severity: string
  description: string
  location: string
  reportedBy: string
  occurredAt: string
  status: string
  weatherRelated: boolean
  actionsTaken: string[]
  preventionMeasures: string[]
}

export class WeatherService {
  // 获取城市天气
  static async getWeatherByCity(city: string): Promise<WeatherData> {
    try {
      const response = await axios.get<ApiResponse<WeatherData>>(`${API_BASE}/weatherapi/city/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取天气失败')
    } catch (error) {
      console.error('获取天气失败:', error)
      throw error
    }
  }

  // 获取增强版天气信息
  static async getEnhancedWeather(city: string): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/enhancedweather/enhanced/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取增强版天气失败')
    } catch (error) {
      console.error('获取增强版天气失败:', error)
      throw error
    }
  }

  // 获取多城市天气对比
  static async getMultiCityWeather(cities: string[]): Promise<any[]> {
    try {
      // 构建查询参数，确保数组参数正确传递
      const params = new URLSearchParams()
      cities.forEach(city => params.append('cities', city))
      
      const response = await axios.get<ApiResponse<any[]>>(`${API_BASE}/enhancedweather/compare?${params.toString()}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取多城市天气失败')
    } catch (error) {
      console.error('获取多城市天气失败:', error)
      throw error
    }
  }

  // 获取天气趋势分析
  static async getWeatherTrends(city: string, days: number = 7): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/enhancedweather/trends/${city}`, {
        params: { days }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取天气趋势失败')
    } catch (error) {
      console.error('获取天气趋势失败:', error)
      throw error
    }
  }

  // 获取生活指数
  static async getLifeIndices(city: string): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/enhancedweather/life-indices/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取生活指数失败')
    } catch (error) {
      console.error('获取生活指数失败:', error)
      throw error
    }
  }

  // 获取7天天气预报
  static async getWeatherForecast(city: string): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/enhancedweather/forecast/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取7天预报失败')
    } catch (error) {
      console.error('获取7天预报失败:', error)
      throw error
    }
  }

  // 获取指定日期的详细预报
  static async getDailyDetailedForecast(city: string, date: string): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/enhancedweather/forecast/${city}/daily/${date}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取详细预报失败')
    } catch (error) {
      console.error('获取详细预报失败:', error)
      throw error
    }
  }

  // 通过坐标获取天气
  static async getWeatherByCoordinates(lat: number, lon: number): Promise<WeatherData> {
    try {
      const response = await axios.get<ApiResponse<WeatherData>>(`${API_BASE}/weatherapi/coordinates`, {
        params: { lat, lon }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取天气失败')
    } catch (error) {
      console.error('通过坐标获取天气失败:', error)
      throw error
    }
  }

  // 获取天气预警
  static async getWeatherAlerts(city: string): Promise<WeatherAlert[]> {
    try {
      const response = await axios.get<ApiResponse<WeatherAlert[]>>(`${API_BASE}/weatherapi/alerts/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      return []
    } catch (error) {
      console.error('获取天气预警失败:', error)
      return []
    }
  }

  // 获取天气摘要
  static async getWeatherSummary(city: string): Promise<WeatherSummary> {
    try {
      const response = await axios.get<ApiResponse<WeatherSummary>>(`${API_BASE}/weatherapi/summary/${city}`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取天气摘要失败')
    } catch (error) {
      console.error('获取天气摘要失败:', error)
      throw error
    }
  }

  // 分析生产影响
  static async analyzeProductionImpact(city: string, activityType: string = '户外作业'): Promise<ProductionImpact> {
    try {
      const response = await axios.get<ApiResponse<ProductionImpact>>(`${API_BASE}/weatherapi/production-impact`, {
        params: { city, activityType }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '分析生产影响失败')
    } catch (error) {
      console.error('分析生产影响失败:', error)
      throw error
    }
  }

  // 多城市天气对比
  static async compareCitiesWeather(cities: string[]): Promise<WeatherData[]> {
    try {
      const citiesStr = cities.join(',')
      const response = await axios.get<ApiResponse<WeatherData[]>>(`${API_BASE}/weatherapi/compare`, {
        params: { cities: citiesStr }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      return []
    } catch (error) {
      console.error('对比城市天气失败:', error)
      return []
    }
  }

  // 测试MCP连接
  static async testMcpConnection(): Promise<any> {
    try {
      const response = await axios.get(`${API_BASE}/mcptest/test`)
      return response.data
    } catch (error) {
      console.error('测试MCP连接失败:', error)
      throw error
    }
  }

  // 获取服务器信息
  static async getServerInfo(): Promise<any> {
    try {
      const response = await axios.get(`${API_BASE}/mcptest/info`)
      return response.data
    } catch (error) {
      console.error('获取服务器信息失败:', error)
      throw error
    }
  }

  // 测试计算器
  static async testCalculator(a: number, operation: string, b: number): Promise<any> {
    try {
      const response = await axios.get(`${API_BASE}/mcptest/calculate`, {
        params: { a, operation, b }
      })
      return response.data
    } catch (error) {
      console.error('测试计算器失败:', error)
      throw error
    }
  }

  // 生产数据相关API
  // 获取生产数据概览
  static async getProductionDashboard(): Promise<ProductionDashboard> {
    try {
      const response = await axios.get<ApiResponse<ProductionDashboard>>(`${API_BASE}/production/dashboard`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取生产概览失败')
    } catch (error) {
      console.error('获取生产概览失败:', error)
      throw error
    }
  }

  // 获取生产订单
  static async getProductionOrders(): Promise<ProductionOrder[]> {
    try {
      const response = await axios.get<ApiResponse<ProductionOrder[]>>(`${API_BASE}/production/orders`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      return []
    } catch (error) {
      console.error('获取生产订单失败:', error)
      return []
    }
  }

  // 获取设备状态
  static async getEquipmentStatus(): Promise<EquipmentStatus[]> {
    try {
      const response = await axios.get<ApiResponse<EquipmentStatus[]>>(`${API_BASE}/production/equipment`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      return []
    } catch (error) {
      console.error('获取设备状态失败:', error)
      return []
    }
  }

  // 获取设备健康状态
  static async getEquipmentHealth(equipmentId: string): Promise<EquipmentHealth> {
    try {
      const response = await axios.get<ApiResponse<EquipmentHealth>>(`${API_BASE}/production/equipment/${equipmentId}/health`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取设备健康状态失败')
    } catch (error) {
      console.error('获取设备健康状态失败:', error)
      throw error
    }
  }

  // 获取安全事件
  static async getSafetyIncidents(): Promise<SafetyIncident[]> {
    try {
      const response = await axios.get<ApiResponse<SafetyIncident[]>>(`${API_BASE}/production/safety/incidents`)
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      return []
    } catch (error) {
      console.error('获取安全事件失败:', error)
      return []
    }
  }

  // 分析天气对生产的影响
  static async analyzeWeatherImpact(city: string, activityType: string = '户外作业'): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/production/weather-impact`, {
        params: { city, activityType }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '分析天气影响失败')
    } catch (error) {
      console.error('分析天气影响失败:', error)
      throw error
    }
  }

  // 获取生产建议
  static async getProductionRecommendations(city: string, activityType: string = '户外作业'): Promise<any> {
    try {
      const response = await axios.get<ApiResponse<any>>(`${API_BASE}/production/recommendations`, {
        params: { city, activityType }
      })
      if (response.data.success && response.data.data) {
        return response.data.data
      }
      throw new Error(response.data.error || '获取生产建议失败')
    } catch (error) {
      console.error('获取生产建议失败:', error)
      throw error
    }
  }


}

export default WeatherService 